import $store from '@/store/index.js'
import router from '@/router/RouterIndex.js'
import {
	isArray
} from '@/utils/object.js'

export default function Authentication(to, hasAuthenticationCallback, noAuthenticationCallback, notFoundCallback) {
	hasAuthenticationCallback = hasAuthenticationCallback || (() => {})
	noAuthenticationCallback = noAuthenticationCallback || (() => {})
	notFoundCallback = notFoundCallback || (() => {})
	if (router.hasRoute(to.name)) {
		if (to.meta.authentication) {
			let currentAdmin = $store.state.admin.admin
			if (currentAdmin === false) {
				//是false，说明正在登录，过一会儿再进行判断
				setTimeout(() => {
					Authentication(to, hasAuthenticationCallback, noAuthenticationCallback)
				}, 100)
			} else {
				//是null，说明登录失败，跳转登录页面
				if (currentAdmin === null) {
					next("/adminLogin")
				} else if (typeof currentAdmin === 'object') {
					let role = currentAdmin.role
					if (typeof to.meta.authentication === 'function') {
						let res = to.meta.authentication(role, to)
						if (typeof res === 'boolean') {
							if (res) {
								hasAuthenticationCallback()
							} else {
								noAuthenticationCallback()
							}
						} else if (isArray(res)) {
							if (res.includes(role)) {
								hasAuthenticationCallback()
							} else {
								noAuthenticationCallback()
							}
						} else if (res instanceof Promise) {
							res.then(next).catch(e => {
								noAuthenticationCallback()
							})
						}
					} else if (isArray(to.meta.authentication)) {
						if (to.meta.authentication.includes(role)) {
							hasAuthenticationCallback()
						} else {
							noAuthenticationCallback()
						}
					}
				}
			}
		} else {
			hasAuthenticationCallback()
		}
	} else {
		notFoundCallback()
	}
}
